<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.timeFrameConfig_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot-scope="{ row }" slot="timeFrameForm">
        <el-time-picker is-range v-model="form.timeFrame" format="HH:mm" range-separator="至"> </el-time-picker>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/quality/timeFrameConfig';
import { mapGetters } from 'vuex';
import moment from 'moment';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'TimeFrameConfig',
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'TIME_FRAME_CONFIG',
      importConfig: {
        show: false
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tableOption: {},
      timer: new Date().getTime(),
      selectionList: [],
      data: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 140,
        searchLabelWidth: 140,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText: '查看',
        viewTitle: '查看',
        selection: true,
        dialogClickModal: false,
        dialogWidth: 800,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '巡检时段名称',
            prop: 'timeframeName',
            search: true,
            row: true,
            rules: [
              {
                required: true,
                message: '请输入巡检时段名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '巡检时段',
            prop: 'timeFrame',
            row: true,
            formslot: true,
            rules: [
              {
                required: true,
                message: '请输入巡检时段',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            row: true
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.timeFrameConfig_add, false),
        viewBtn: this.vaildData(this.permission.timeFrameConfig_view, false),
        delBtn: this.vaildData(this.permission.timeFrameConfig_delete, false),
        editBtn: this.vaildData(this.permission.timeFrameConfig_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      if (row.timeFrame.length > 0) {
        row.startTime = moment(row.timeFrame[0]).format('HH:mm');
        row.endTime = moment(row.timeFrame[1]).format('HH:mm');
      }
      delete row.timeFrame;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      if (row.timeFrame.length > 0) {
        row.startTime = moment(row.timeFrame[0]).format('HH:mm');
        row.endTime = moment(row.timeFrame[1]).format('HH:mm');
      }
      delete row.timeFrame;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          let data = res.data.data;
          this.form = data;
          console.log(data.startTime.split(':'));
          this.form.timeFrame = [new Date(2023, 0, 0, ...data.startTime.split(':')), new Date(2023, 0, 0, ...data.endTime.split(':'))];
          console.log(this.form.timeFrame);
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this._forEach(data.records, (item) => {
          item.timeFrame = item.startTime + '-' + item.endTime;
        });
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
